import axios from 'axios'
import { message } from 'ant-design-vue';
import router from '@/router';

const service = axios.create({
  baseURL: "http://127.0.0.1:8081",
  timeout: 5000
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 添加请求头等前置处理
    config.headers['Authorization'] = localStorage.getItem('authorization')
    return config
  },
  error => {
    // 请求错误处理
    console.log('Request Error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    if (response.data.code === 200) {
      return Promise.resolve(response.data)
    } else {
      message.error(response.data.message)
      return Promise.reject(response.data)
    }
  },
  error => {
    console.log(error)
    if (error.response.status === 403) {
      // 跳转到登录页
      message.error('请先登录！')
      router.push( {name: 'main'} )
      return Promise.reject(error.data)
    } else {
      message.error('接口错误!' + error.message)
      return Promise.reject(error)
    }
  }
)

export default service